package com.yuqih.common.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.lang3.StringUtils;

public class IpUtils {

	/**
	 * 根据某个http和ip相关header值获取http请求的远程ip，如果不是有效的ip地址则返回null
	 * 
	 * @param ip
	 * @return
	 */
	public static String getHttpRemoteIp(String ipHeader) {
		if (StringUtils.isBlank(ipHeader) || StringUtils.equalsIgnoreCase("unknown", ipHeader)) {
			return null;
		}

		if (StringUtils.indexOf(ipHeader, ",") != -1) {
			return StringUtils.left(StringUtils.split(ipHeader, ",")[0], 15);
		}
		return ipHeader;
	}

	/**
	 * 获取一个本机ip
	 * 
	 * @return 一个本机IP
	 * @throws SocketException
	 */
	public static String getLocalIp() throws SocketException {

		String localip = null;// 本地IP，如果没有配置外网IP则返回它
		String netip = null;// 外网IP

		Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		boolean finded = false;// 是否找到外网IP

		while (netInterfaces.hasMoreElements() && !finded) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();

			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (ip.isLoopbackAddress() || ip.getHostAddress().indexOf(":") != -1) {
					continue;
				}
				
				if (!ip.isSiteLocalAddress()) {// 外网IP
					netip = ip.getHostAddress();
					finded = true;
					break;
				} else {// 内网IP
					localip = ip.getHostAddress();
				}
			}
		}

		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}

	}
}
